﻿using BookManege.entity;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;

namespace BookManege.service
{
    internal class UserManegeService
    {
        private MySqlConnection MySqlConnection;
        public UserManegeService()
        {
            MySqlConnection = DatabaseUtil.GetMysqlConnection();
        }
        public int GetCount()
        {
            return Convert.ToInt32( DatabaseUtil.SelectUtil("SELECT count(1) as count FROM user"));
        }
        public DataTable GetAllUser(int pageNum,int pageSize)
        {
            return DatabaseUtil.GetDataTable("select * from user limit " + ((pageNum - 1) * pageSize) + "," + pageSize);
        }
        public DataTable GetAllUser()
        {
            return DatabaseUtil.GetDataTable("select * from user");
        }
        public int DeleteUser(long id)
        {
            return DatabaseUtil.MyExecuteNonQuery("delete from user where id = " + id);
        }
        public int UpdateUser(User user)
        {
            return DatabaseUtil.MyExecuteNonQuery("update user set avatar='" + user.Avatar + "',user_name='" + user.UserName +
                "',nick_name = '" + user.NickName + "',sex = " + user.Sex + ",age=" + user.Age + ",phone=" + user.Phone + ",email='" + user.Email + "' where id=" + user.Id);
        }
        public DataTable Search(string userName, int phone, long id, int sex, int authority)
        {
            return DatabaseUtil.GetDataTable("select * from user where 1=1 " +
              (userName != "" ? " and user_name like '%" + userName + "%'" : "") +
              (phone != 99 ? " and phone =" + phone : "") +
              (sex != 99 ? " and sex =" + sex : "") +
              (authority != 99 ? " and authority =" + authority : ""));
        }
        public string ResetPassword(long id)
        {
            string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random rnd = new ();
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i < 10; i++)
            {
                builder.Append(valid[rnd.Next(valid.Length)]);
            }
            string newPassWord = builder.ToString();
            string sql = "update user set password = '" + newPassWord + "' where id=" + id;
            MySqlCommand mySqlCommand = new (sql, MySqlConnection);

            return mySqlCommand.ExecuteNonQuery()>0? newPassWord:"";
        }
        public int GetExceedDateCount()
        {
            return Convert.ToInt32(DatabaseUtil.SelectUtil("SELECT count(1) FROM still_application WHERE state='0'"));
        }

    }
}
